package com.gitee.ty850454.leetcode1047;


/**
 *
 * @author xy
 */
public class Leetcode1047 {

    public static void main(String[] args) {
        String result = new Leetcode1047().removeDuplicates("aaaaaaaa");
        System.out.println(result);
    }

    public String removeDuplicates(String S) {
        char[] source = S.toCharArray();
        char[] target = arrayToHeavy(source);
        for (; source.length != target.length; target = arrayToHeavy(source)) {
            source = target;
        }
        return new String(target);
    }


    private char[] arrayToHeavy(char[] source) {
        char[] target = new char[source.length];
        int targetSize = 0;

        char last = 0;
        for (char c : source) {
            if (last != 0) {
                if (c != last) {
                    target[targetSize++] = last;
                } else {
                    last = 0;
                    continue;
                }
            }
            last = c;
        }
        if (last != 0) {
            target[targetSize++] = last;
        }
        char[] result = new char[targetSize];
        System.arraycopy(target, 0, result, 0, targetSize);
        return result;
    }
}
